package main.java.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//定义一个矩形类
class Rect implements Comparable<Rect>{//矩形
    private Integer width;
    private Integer height;
    public Rect() {
    }
    public Rect(Integer width, Integer height) {
        this.width = width;
        this.height = height;
    }
    //实现Comparable接口
    @Override
    public int compareTo(Rect o) {
        //这里按照矩形的宽度进行比较
        return this.width.compareTo(o.width);
    }
    //重写toString方法
    @Override
    public String toString() {
        return "Rect{" +
                "width=" + width +
                ", height=" + height +
                '}';
    }

}

public class CollectionSortDemo2 {
    public static void main(String[] args) {
        //定义矩形对象
        Rect p1 = new Rect(10, 20);
        Rect p2 = new Rect(5, 15);
        Rect p3 = new Rect(8, 36);
        //创建一个List集合
        List<Rect> list = new ArrayList<>();
        //添加矩形对象
        list.add(p1);
        list.add(p2);
        list.add(p3);
        //调用Collections集合的sort方法对集合元素进行排序
        //List集合中的元素必须实现Comparable接口
        Collections.sort(list);
        //打印排序后的结果
        System.out.println(list);
    }
}
